'''
Created on Apr 20, 2011

@author: riche
'''

from ft.framework import component

class LoginComp(component.Implementation):
    '''
    classdocs
    '''

    BAD_CMD_MSG = 'ERROR:BAD LOGIN COMMAND'
    BAD_USR_MSG = 'ERROR:USER HAS NOT LOGGED ON '

    LOGIN_CMD = 'LOGIN'
    WORK_CMD = 'WORK'

    def __init__(self, name):
        '''
        Constructor
        '''
        component.Implementation.__init__(self, name)
        self.add_port(component.Port('in', 'process_request'))
        self.add_port(component.Port('pass_through', '__OUT__'))
        self.add_port(component.Port('error', '__OUT__'))
        self._users = []
        
    def process_request(self, msg):
        #print(msg)
        req = msg.strip().split(':')
        cmd = req[0]
        if cmd == LoginComp.LOGIN_CMD:
            usr = req[1]
            if usr not in self._users:
                self._users.append(usr)
        elif cmd == LoginComp.WORK_CMD:
            usr = req[1]
            if usr in self._users:
                out_msg = ':'.join(req[2:])
                self.send_out('pass_through', out_msg)
            else:
                self.send_out('error', LoginComp.BAD_USR_MSG + usr)
        else:
            self.send_out('error', LoginComp.BAD_CMD_MSG)